package main

import (
	"go-micro.dev/v4"
	"go-micro.dev/v4/logger"

	"gitee.com/go-micro-services/user/domain/repository"
	"gitee.com/go-micro-services/user/domain/service"
	"gitee.com/go-micro-services/user/handler"
	pbuser "gitee.com/go-micro-services/user/proto/user"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

var (
	serviceName = "go.micro.service.user"
	version     = "latest"
)

func main() {
	// 1. 创建服务
	srv := micro.NewService()
	srv.Init(
		micro.Name(serviceName),
		micro.Version(version),
	)

	// 2. 创建数据库连接
	db, dbErr := gorm.Open("mysql", "root:123456_mysql@tcp(localhost:3307)/micro?charset=utf8&parseTime=True&loc=Local")

	if dbErr != nil {
		logger.Fatal(dbErr)
	}

	defer db.Close()

	db.SingularTable(false) // true 则 表就是单数

	// 数据库表初始化，只执行一次, 如果本来就设计好了，则无需下面2行
	// rp := repository.NewUserRepository(db)
	// rp.InitTable()

	// 3. 创建服务实例
	userDataService := service.NewUserDataService(repository.NewUserRepository(db))

	// 4. 注册 handler
	if handlerErr := pbuser.RegisterUserHandler(srv.Server(), &handler.User{UserDataService: userDataService}); handlerErr != nil {
		logger.Fatal(handlerErr)
	}

	// 5. 运行服务
	if runErr := srv.Run(); runErr != nil {
		logger.Fatal(runErr)
	}
}
